
// 定义环境变量
var isWX = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/);
var isQQ = navigator.userAgent.match(/QQ\/([\d\.]+)/);
var require;

// 导入微信、QQ的api
var wxapi = "//res.wx.qq.com/open/js/jweixin-1.0.0.js";
var qqapi = "//open.mobile.qq.com/sdk/qqapi.js?_bid=152";
//动态引入api并执行js
function _require(url, onload) {

    var doc = document;
    var head = doc.head || (doc.getElementsByTagName("head")[0] || doc.documentElement);
    var node = doc.createElement("script");
    node.onload = onload;
    node.onerror = function() {
    };
    node.async = true;
    node.src = url[0];
    head.appendChild(node);
}


// 配置分享内容
window.initShareConf = function (title, summary, pic, url, reportData) {

    if(summary==""||summary==null||typeof(summary)=="undefined"){
        summary="上【扬帆】客户端参与互动交流";
    }
    require = _require;
    window.setShareInfo = init;


    if (isWX) {
        /************** 微信签名等参数获取 ***************/
        var pageUrl = window.location.href;
        var conUrls = location.href.split("#");
        var conUrl = "";
        if (conUrls.length > 2) {
            conUrl = conUrls[0] + conUrls[1];
        } else {
            conUrl = pageUrl;
        }
        if (!window.yfH5SecondShareConfig)
        // 定义签名参数数据结构
            window.yfH5SecondShareConfig = {
                timestamp: null,
                noncestr: null,
                signature: null,
                appid: "wxad55f090d8fcd385"
            };
        var par = {
            url: conUrl
        };


            $.ajax({
                type: "POST",
               // contentType: "application/json;charset=utf-8",
                url: location.protocol+"//admin.96189.com/urc/external/share",
                data: par,
                dataType: "JSON",
                async: false,
                success: function (data) {


                    if (!data.state || !data.result || data.state.rc != 0) {
                        console.error("后台返回的参数不正确");
                        return;
                    }
                    // 获取签名参数数据

                    window.yfH5SecondShareConfig.timestamp = data.result.timestamp;
                    window.yfH5SecondShareConfig.noncestr = data.result.noncestr;
                    window.yfH5SecondShareConfig.signature = data.result.signature;
                }
            });



        /************** 微信配置分享内容 ***************/
        setShareInfo({
            title: title,// 标题
            summary: summary,// 摘要
            pic: "http://yztv-vod.homecdn.com/2562aac2bebd4e75a0dadb7c60e1e8dc.png",// 图标地址
            url: url,// 分享地址
            id: "111111",
            reportdata: reportData,
            WXconfig: {
                // 微信签名等参数配置
                swapTitleInWX: false,
                appId: yfH5SecondShareConfig.appid,
                timestamp: yfH5SecondShareConfig.timestamp,
                nonceStr: yfH5SecondShareConfig.noncestr,
                signature: yfH5SecondShareConfig.signature
            }
        });
    } else if (!isQQ) {
        /************** QQ配置分享内容 ***************/
        $("meta[name='name']").attr('content', title);          // QQ二次分享标题显示
        $("meta[name='description']").attr('content', summary); // QQ二次分享摘要显示

    }

}

// 手机QQ分享：meta.name(name/description)、获取第一个<img />标签
// <meta name="name" itemprop="name" content="扬帆" />
// <meta name="description"  content="扬帆" />

//配置微信
function _initWX(data) {

    if (!data.WXconfig) {
        return;
    }

    // 二次分享替换图片为固定logo
    data.pic = "http://yztv-vod.homecdn.com/2562aac2bebd4e75a0dadb7c60e1e8dc.png";

    require([wxapi], function (wx) {    // ??

        if (!wx.config) {
            wx = window.wx;
        }
        var conf = data.WXconfig;   // conf: window.yfH5SecondShareConfig
        wx.config({
            debug: false,
            appId: conf.appId,
            timestamp: conf.timestamp,
            nonceStr: conf.nonceStr,
            signature: conf.signature,
            jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone"]
        });
        wx.error(function (res) {
            // error
        });
        wx.ready(function () {

            var config = {
                title: data.title,  // data: 分享信息的相关参数对象
                desc: data.summary,
                link: data.url,
                imgUrl: data.pic,
                type: "",
                dataUrl: "",
                success: function () {
                    data.callback && data.callback();

                    // TODO：微信分享回调--统计用户行为
                    shareUrlReport(data.reportdata, "share");
                },
                cancel: function () {

                }
            };
            wx.onMenuShareAppMessage(config);
            wx.onMenuShareQQ(config);
            wx.onMenuShareQZone(config);
            if (conf.swapTitleInWX) {
                wx.onMenuShareTimeline({
                    title: data.summary,
                    desc: data.title,
                    link: data.url,
                    imgUrl: data.pic,
                    type: "",
                    dataUrl: "",
                    success: function () {
                        data.callback && data.callback();
                    },
                    cancel: function () {
                    }
                });
            } else {
                wx.onMenuShareTimeline(config);
            }

        });
    });
}

// 配置QQ
function _initQQ(data) {
    var info = {title: data.title, desc: data.summary, share_url: data.url, image_url: data.pic};
    function doQQShare() {
        try {
            if (data.callback) {
                data.WXconfig.swapTitleInWX = false;
                window.mqq.ui.setOnShareHandler(function (type) {
                    if (type == 3 && (data.swapTitle || data.WXconfig && data.WXconfig.swapTitleInWX)) {
                        info.title = data.summary;
                    } else {
                        info.title = data.title;
                    }
                    info.share_type = type;
                    info.back = true;
                    window.mqq.ui.shareMessage(info, function (result) {
                        if (result.retCode === 0) {
                            data.callback && data.callback.call(this, result);

                            // TODO：QQ分享回调--统计用户行为
                            shareUrlReport(data.reportData, "share");
                        }
                    });
                });
            } else {

                /*QQ分享要求分享页面与调用qq分享js的页面域名完全一致。
                由于分享的入口域名为t短域名，和h5页面的share域名不一致。出现分享设置参数无效的情况。
                目前暂时先注释掉调用接口。*/
                window.mqq.data.setShareInfo(info);
            }
        } catch (e) {

        }
    }

    if (window.mqq) {
        doQQShare();
    } else {

        require([qqapi], function () {
            doQQShare();
        });
    }
}

// 当该页面在微信中打开时，init方法会自动注册以上配置。
function init(opts) {
    isWX && _initWX(opts);
    isQQ && _initQQ(opts);

}

